//
//  DeviceViewController.m
//  sentorise
//
//  Created by admin on 2025/8/22.
//

#import "DeviceViewController.h"
#import "DeviceItemTableViewCell.h"
#import "GlobalDefine.h"
#import "DeviceAddView.h"
#import "BTManager.h"
#import "DeviceDataInfoViewController.h"
#import "BlutoothGroupModel.h"
#import "DeviceScanResultViewController.h"

@interface DeviceViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UILabel *deviceNumLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *addLabel;

@property (nonatomic, strong) NSMutableArray<BlutoothModel *> *dataSource;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *batteryLevelSource;

@end

@implementation DeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [[NSMutableArray alloc] init];
    self.batteryLevelSource = [[NSMutableArray alloc] init];
    self.isCurrentPage = YES;
    
    self.titleLabel.text = NSLocalizedString(@"My device ", nil);
    self.addLabel.text = NSLocalizedString(@"Add", nil);

    [[BTManager sharedBTManager] startScan];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices) name:kBTSearchDevices object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:@"BatteryBluListDidChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadBatteryLevel:) name:kBTGetBatteryLevel object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevicesName:) name:kBTSearchDevicesName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissAddView) name:kBTAddViewDismiss object:nil];

    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceItemTableViewCell" bundle:nil] forCellReuseIdentifier:@"DeviceItemTableViewCell"];
    
    [self reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[BTManager sharedBTManager] stopScan];
    self.isCurrentPage = NO;
    [BTManager sharedBTManager].isGettingBattery = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.isCurrentPage && ![BTManager sharedBTManager].isGettingBattery && [BTManager sharedBTManager].lookSocBlues.count) {
        [BTManager sharedBTManager].isGettingBattery = YES;
    }
}

- (void)dismissAddView {
    self.isCurrentPage = YES;
    if (self.isCurrentPage && ![BTManager sharedBTManager].isGettingBattery && [BTManager sharedBTManager].lookSocBlues.count) {
        [BTManager sharedBTManager].isGettingBattery = YES;
    }
}

- (void)reloadData {
    [self.dataSource removeAllObjects];
    
    NSString *listStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"BatteryBluList"] ?: @"";
    if (listStr.length) {
        NSArray *dataArray = [BlutoothModel covertToModelList:listStr];
        [self.dataSource addObjectsFromArray:dataArray];
    }
    
    [self searchDevices];
}

- (IBAction)actionAdd:(id)sender {
    self.isCurrentPage = NO;
    [BTManager sharedBTManager].isGettingBattery = NO;
    [DeviceAddView show:self.nv];
}

- (void)searchDevices {
    [self.tableView reloadData];
    NSInteger nums = 0;
    NSMutableArray *arr = [NSMutableArray array];
    for (BlutoothModel *m in self.dataSource) {
        for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
            if ([p.identifier.UUIDString isEqualToString:m.uuid]) {
                nums += 1;
                [arr addObject:p];
                break;
            }
        }
    }
    self.deviceNumLabel.text = [NSString stringWithFormat:@"%ld/%ld", nums, self.dataSource.count];
    if (!self.isCurrentPage) {
        return;
    }
    if (arr.count && [BTManager sharedBTManager].lookSocBlues.count != arr.count) {
        [BTManager sharedBTManager].lookSocBlues = arr;
        if (![BTManager sharedBTManager].isGettingBattery) {
            [BTManager sharedBTManager].isGettingBattery = YES;
        }
    }
}

- (void)reloadBatteryLevel:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.batteryLevelSource removeAllObjects];
    [self.batteryLevelSource addObjectsFromArray:list];
    [self.tableView reloadData];
}

- (void)searchDevicesName:(NSNotification *)nf {
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceItemTableViewCell *cell = (DeviceItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceItemTableViewCell"];
    BOOL isOnline = NO;
    for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
        if ([p.identifier.UUIDString isEqualToString:self.dataSource[indexPath.section].uuid]) {
            isOnline = YES;
            break;
        }
    }
    cell.isOnline = isOnline;
    NSString *name = [[BTManager sharedBTManager].diviceNameDict objectForKey:self.dataSource[indexPath.section].name];
    name = name.length>0 ? name : self.dataSource[indexPath.section].name;
    cell.nameLabel.text = name;
    NSString *soc = @"0";
    for (NSDictionary *dict in self.batteryLevelSource) {
        if ([[dict objectForKey:@"name"] isEqualToString:self.dataSource[indexPath.section].name]) {
            soc = [dict objectForKey:@"soc"];
            break;
        }
    }
    cell.socLabel.text = [NSString stringWithFormat:@"%@%% SOC", soc];
    NSInteger socInt = [soc integerValue];
    if (socInt == 0) {
        cell.socIV.image = [UIImage imageNamed:@"soc_0"];
    }else if (socInt == 100) {
        cell.socIV.image = [UIImage imageNamed:@"soc_6"];
    }else if (socInt < 20) {
        cell.socIV.image = [UIImage imageNamed:@"soc_1"];
    }else if (socInt < 40) {
        cell.socIV.image = [UIImage imageNamed:@"soc_2"];
    }else if (socInt < 60) {
        cell.socIV.image = [UIImage imageNamed:@"soc_3"];
    }else if (socInt < 80) {
        cell.socIV.image = [UIImage imageNamed:@"soc_4"];
    }else if (socInt < 100) {
        cell.socIV.image = [UIImage imageNamed:@"soc_5"];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 10)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DeviceDataInfoViewController *vc = [[DeviceDataInfoViewController alloc] initWithNibName:@"DeviceDataInfoViewController" bundle:nil];
    vc.model = self.dataSource[indexPath.section];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"Confirm delete?", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler: nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.dataSource removeObjectAtIndex:indexPath.section];
            NSString *str = [BlutoothModel toJson:self.dataSource];
            [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"BatteryBluList"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self reloadData];
        }]];
        [self presentViewController:alertController animated:true completion:nil];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return NSLocalizedString(@"Delete", nil);
}

@end
